# 使用14b的qwen2.5搭建的工作流进行翻译工作
# 工作流基本设计结构为 “吴恩达教授的开源项目”
# 再对tex翻译功能进行特化
# 注意正常的翻译结果是以UTF-8编码的


import requests
import json

from os import walk


filepath = "./en/"   # Put the English articles in this folder
outfpath = "./cn/"   # The result will be saved in this folder


def translate(source_lang = "English", target_lang = "中文", country = "中国", response_mode="blocking"):

  for (dirpath, dirnames, filenames) in walk(filepath): # 遍历一下文件路径下的东西
    break

  for file in filenames:  # 遍历一下文件名
    with open(filepath + file, 'r') as f:
        text = f.read()
      
        # API URL
        api_url = "http://10.202.160.156/v1/workflows/run"

        # API Key
        api_key = "app-zBLsuO9Af6hoZPrw6cNcqssL"

        # Request headers
        headers = {
            'Authorization': f'Bearer {api_key}',
            'Content-Type': 'application/json',
            "connnection": "close" # 关闭keep-alive连接，以防服务端连接池被占满
        }

        # Request payload
        data = {
            "inputs": {
                "source_text":text,
                "source_lang":source_lang,
                "target_lang":target_lang,
                "country": country
              },
            "response_mode": response_mode,
            "user": "Tool man"
        }

        # Send the POST request
        response = requests.post(api_url, headers=headers, json=data)

        # Check the response
        if response.status_code == 200:
            print("Request successful\n")
            response_json = response.json()
            
            #  把翻译结果保存到文件
            with open(outfpath + file , "w") as f:
               f.write(response_json["data"]["outputs"]["翻译结果"])
          
            # print("Response:", response_json["data"]["outputs"]["翻译结果"])
        else:
            print(f"Request failed with status code: {response.status_code}")
            print("Error:", response.text)


if __name__ == "__main__":
  # 调用函数

  print("Start translating...\nPlease be patient...")

  translate(source_lang="English", target_lang="中文", country = "中国")

  print("Done!")